using System;
using System.Collections.Generic;
using UnityEngine;

namespace PKGames.Audio
{
	public class AudioDataCollection : MonoBehaviour
	{
		protected Dictionary<string, AudioData> _indexedAudioClips = new Dictionary<string, AudioData>();

		[SerializeField]
		private AudioClip _bgm;

		public AudioData[] Sounds;

		private void Awake()
		{
			Init();
			base.gameObject.RemoveCloneFromName();
		}

		protected virtual void OnEnable()
		{
			MonoSingleton<AudioManager>.Instance.RegisterAudioDataCollection(this);
			if (_bgm != null)
			{
				MonoSingleton<AudioManager>.Instance.RegisterAudioDataCollectionBgm(_bgm);
			}
		}

		protected virtual void OnDisable()
		{
			if (MonoSingleton<AudioManager>.Instance != null)
			{
				MonoSingleton<AudioManager>.Instance.UnregisterAudioDataCollection(this);
				if (_bgm != null)
				{
					MonoSingleton<AudioManager>.Instance.UnregisterAudioDataCollectionBgm();
				}
			}
		}

		public AudioData GetAudioDataById(string id)
		{
			try
			{
				return _indexedAudioClips[id];
			}
			catch (Exception)
			{
				return null;
			}
		}

		protected void Init()
		{
			AudioData[] sounds = Sounds;
			foreach (AudioData audioData in sounds)
			{
				_indexedAudioClips[audioData.Id] = audioData;
			}
		}
	}
}
